import router, { resetRouter } from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css' // 进度条样式
import { getToken } from '@/utils/auth' // 从cookie获取令牌
import getPageTitle from '@/utils/get-page-title'
import { getId } from '@/utils/auth'

NProgress.configure({ showSpinner: false }) // NProgress 配置

const whiteList = ['/login', '/register', '/forget', '/login-path'] // 没有重定向白名单

router.beforeEach(async(to, from, next) => {
  // 开始进度条
  NProgress.start()

  // 设置页面标题
  document.title = getPageTitle(to.meta.title)

  // 确定用户是否已登录
  const hasToken = getToken()
  if (hasToken) {
    // *****指定页面缓存 存vuex*****
    if (
      (to.name === 'brand-manage/purchase-order-list-zz' && from.name === 'brand-manage/purchase-order-detail') ||
      (to.name === 'brand-manage/purchase-order-list-fz' && from.name === 'brand-manage/purchase-order-detail') ||
      (to.name === 'service-manage/purchase-order-list-zz' && from.name === 'service-manage/purchase-order-detail') ||
      (to.name === 'service-manage/purchase-order-list-fz' && from.name === 'service-manage/purchase-order-detail') ||
      (to.name === 'supply-manage/discounts' && from.name === 'supply-manage/sign') ||
      (to.name === 'supply-manage/order' && from.name === 'brand-manage/purchase-order-detail') ||
      (to.name === 'supply-manage/group-buying' && (from.name === 'supply-manage/examine' || from.name === 'supply-manage/list')) ||
      (to.name === 'voucher-management/list' && (from.name === 'voucher-management/update' || from.name === 'voucher-management/examine')) ||
      (to.name === 'city-substation/list' && from.name === 'city-substation/update')
    ) {
      store.dispatch('keepAlive/changeKeepAlive')
    } else {
      store.dispatch('keepAlive/changeNoKeepAlive')
    }
    // ***********************
    if (to.path === '/login') {
      // 如果已登录，则重定向到主页
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          await store.dispatch('user/getInfo')
          getId() != 1 && await store.dispatch('account/SET_STATUS')
          const roles = store.getters.roles
          resetRouter()
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          router.addRoutes(accessRoutes)

          // reset visited views and cached views
          store.dispatch('tagsView/delAllViews', null, {
            root: true
          })
          next({ ...to, replace: true })
        } catch (error) {
          // 删除token，进入登录页面重新登录
          console.log('删除token，进入登录页面重新登录')
          store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* 没有 token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // 跳转登录页免验证，直接跳转过去，没有重定向白名单
      next()
    } else {
      // 没有访问权限的其他页面被重定向到登录页面
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 完成进度条
  NProgress.done()
})
